﻿#include "mainwindow.h"

#include <QDebug>
#include <QMouseEvent>
#include <QKeyEvent>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    drawing = false;
    penColor = Qt::black;

    setWindowTitle("Simple Drawing Application");
    resize(1920, 1080);

    // 初始化画布，设置白色背景
    canvas = QImage(size(), QImage::Format_RGB32);
    clearCanvas();
}

MainWindow::~MainWindow()
{
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_C:
        qDebug() << "清空画布";
        clearCanvas();
        break;
    case Qt::Key_R:
        qDebug() << "切换到红色笔";
        penColor = Qt::red;
        break;
    case Qt::Key_G:
        qDebug() << "切换到绿色笔";
        penColor = Qt::green;
        break;
    case Qt::Key_B:
        qDebug() << "切换到蓝色笔";
        penColor = Qt::blue;
        break;
    default:
        QMainWindow::keyPressEvent(event);
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        drawing = true;
        lastPoint = event->pos();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && drawing) {
        drawing = false;

        // 最后一次绘制
        QPainter painter(&canvas);
        painter.setPen(QPen(penColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        painter.drawLine(lastPoint, event->pos());
        update();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons() & Qt::LeftButton) && drawing) {
        QPainter painter(&canvas);
        painter.setPen(QPen(penColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

        // 绘制从上一次位置到当前鼠标位置的线段
        painter.drawLine(lastPoint, event->pos());
        lastPoint = event->pos();
        update();
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawImage(0, 0, canvas); // 将画布绘制到窗口上
}

void MainWindow::clearCanvas()
{
    // 将画布填充为白色
    canvas.fill(Qt::white);
    update(); // 重新绘制窗口
}

